package spe.ui.editor;

import org.eclipse.core.resources.IFile;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorMatchingStrategy;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.ide.ResourceUtil;

public class MatchingStrategy implements IEditorMatchingStrategy
{

	@Override
	public boolean matches(IEditorReference editorRef, IEditorInput input) 
	{
		System.out.println("I GET HEREEEEEEEEEEEEEEEEEEEEEEEEE");
		IFile inputFile = ResourceUtil.getFile(input);
		if (inputFile == null || !(input instanceof IFileEditorInput))
			return false;
		
    	String inputFilePath = inputFile.getFullPath().removeLastSegments(1).toString();
        String inputFileName = inputFile.getFullPath().lastSegment();
        try {
            IFile editorFile = ResourceUtil.getFile(editorRef.getEditorInput());
            if (editorFile == null)
            	return false;
            
            String editorFilePath = editorFile.getFullPath().removeLastSegments(1).toString();
            
            if (!editorFilePath.equals(inputFilePath))
            	return false;
            
            
            if (inputFileName.equals("spe-model.xml"))
            	return true;
            
            String editorFileName = editorFile.getFullPath().lastSegment();
            return matches(editorFileName, inputFileName);
        } catch (PartInitException e) 
        {
        	e.printStackTrace();
            return false;
        }
	}
	
	private boolean matches(String left, String right) 
	{
		if (right.indexOf(".gpd.") == 0) {
			return left.equals(right.substring(5));
		} else {
			return right.equals(left);
		}
	}

}
